예제 #1
0
        private static async Task CreateOrUpdateIndividualEnrollmentAsync()
        {
            try
            {
                using (var provisioningServiceClient =
                           ProvisioningServiceClient.CreateFromConnectionString(dpsConnectionString))
                {
                    Console.WriteLine("Connected to sample provisioning service successfully.");
                    // Create a new individualEnrollment config
                    Console.WriteLine();
                    Attestation          attestation          = new TpmAttestation(tpmEndorsementKey);
                    IndividualEnrollment individualEnrollment = new IndividualEnrollment(registrationId, attestation)
                    {
                        DeviceId           = optionalDeviceId,
                        ProvisioningStatus = optionalProvisioningStatus
                    };

                    // Create the individualEnrollment
                    Console.WriteLine("Adding new individualEnrollment...");
                    IndividualEnrollment individualEnrollmentResult =
                        await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);

                    Console.WriteLine("IndividualEnrollment created :");
                    Console.WriteLine(individualEnrollmentResult);
                }
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
            }
        }
예제 #2
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);
            }
        }
예제 #3
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);
            }
        }
예제 #4
0
        /// <summary>
        /// A sample to manage enrollment groups in device provisioning service.
        /// </summary>
        /// <param name="args">
        /// Run with `--help` to see a list of required and optional parameters.
        /// </param>
        public static async Task <int> Main(string[] args)
        {
            // Parse application parameters
            Parameters parameters            = null;
            ParserResult <Parameters> result = Parser.Default.ParseArguments <Parameters>(args)
                                               .WithParsed(parsedParams =>
            {
                parameters = parsedParams;
            })
                                               .WithNotParsed(errors =>
            {
                Environment.Exit(1);
            });

            if (string.IsNullOrWhiteSpace(parameters.ProvisioningConnectionString))
            {
                Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(result, null, null));
                Environment.Exit(1);
            }

            using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(parameters.ProvisioningConnectionString);
            var sample = new CleanupEnrollmentsSample(provisioningServiceClient);
            await sample.RunSampleAsync();

            Console.WriteLine("Done.");
            return(0);
        }
예제 #5
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);
            }
        }
예제 #6
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
            }
        }
예제 #7
0
        private static async Task EnrollDeviceInDpsAsync(string dpsConnectionString, string registrationId, string tpmEndorsementKey, string deviceId)
        {
            using (var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(dpsConnectionString))
            {
                Console.WriteLine("\nCreating a new individualEnrollment...");

                var attestation = new TpmAttestation(tpmEndorsementKey);

                var individualEnrollment =
                    new IndividualEnrollment(registrationId.ToLower(), attestation);

                // The following parameters are optional. Remove them if you don't need them.
                individualEnrollment.DeviceId = deviceId;

                // Add this line if you deploy an IoT Edge device
                individualEnrollment.Capabilities =
                    new DeviceCapabilities {
                    IotEdge = true
                };

                individualEnrollment.ProvisioningStatus = ProvisioningStatus.Enabled;

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

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

                Console.WriteLine("\nIndividualEnrollment created with success.");
                Console.WriteLine(individualEnrollmentResult);
            }
        }
예제 #8
0
        public async Task ProvisioningServiceClient_QueryInvalidServiceCertificateHttp_Fails()
        {
            using (var provisioningServiceClient =
                       ProvisioningServiceClient.CreateFromConnectionString(
                           Configuration.Provisioning.ConnectionStringInvalidServiceCertificate))
            {
                Query q = provisioningServiceClient.CreateEnrollmentGroupQuery(
                    new QuerySpecification("SELECT * FROM enrollmentGroups"));

                var exception = await Assert.ThrowsExceptionAsync <ProvisioningServiceClientTransportException>(
                    () => q.NextAsync()).ConfigureAwait(false);

#if NET47 || NET451
                Assert.IsInstanceOfType(exception.InnerException.InnerException.InnerException, typeof(AuthenticationException));
#elif NETCOREAPP2_0
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // WinHttpException (0x80072F8F): A security error occurred
                    Assert.AreEqual(unchecked ((int)0x80072F8F), exception.InnerException.InnerException.HResult);
                }
                else
                {
                    // CURLE_SSL_CACERT (60): Peer certificate cannot be authenticated with known CA certificates.
                    Assert.AreEqual(60, exception.InnerException.InnerException.HResult);
                }
#else
                Assert.IsInstanceOfType(exception.InnerException.InnerException, typeof(AuthenticationException));
#endif
            }
        }
        /// <summary>
        /// A sample to manage enrollment groups in device provisioning service.
        /// </summary>
        /// <param name="args">
        /// Run with `--help` to see a list of required and optional parameters.
        /// </param>
        public static int Main(string[] args)
        {
            // Parse application parameters
            Parameters parameters            = null;
            ParserResult <Parameters> result = Parser.Default.ParseArguments <Parameters>(args)
                                               .WithParsed(parsedParams =>
            {
                parameters = parsedParams;
            })
                                               .WithNotParsed(errors =>
            {
                Environment.Exit(1);
            });

            if (string.IsNullOrWhiteSpace(parameters.ProvisioningConnectionString))
            {
                Console.WriteLine(CommandLine.Text.HelpText.AutoBuild(result, null, null));
                Environment.Exit(1);
            }

            X509Certificate2 certificate = new X509Certificate2(parameters.CertificatePath);

            using (var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(parameters.ProvisioningConnectionString))
            {
                var sample = new EnrollmentGroupSample(provisioningServiceClient, certificate);
                sample.RunSampleAsync().GetAwaiter().GetResult();
            }

            Console.WriteLine("Done.\n");
            return(0);
        }
        public async Task ProvisioningServiceClient_GetIndividualEnrollmentAttestation(AttestationMechanismType attestationType)
        {
            ProvisioningServiceClient provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString);
            IndividualEnrollment individualEnrollment = await CreateIndividualEnrollment(provisioningServiceClient, attestationType, null, AllocationPolicy.Static, null, null, null);

            AttestationMechanism attestationMechanism = await provisioningServiceClient.GetIndividualEnrollmentAttestationAsync(individualEnrollment.RegistrationId);

            if (attestationType == AttestationMechanismType.SymmetricKey)
            {
                Assert.AreEqual(AttestationMechanismType.SymmetricKey, attestationMechanism.Type);
                SymmetricKeyAttestation symmetricKeyAttestation = (SymmetricKeyAttestation)attestationMechanism.GetAttestation();
                Assert.AreEqual(((SymmetricKeyAttestation)individualEnrollment.Attestation).PrimaryKey, symmetricKeyAttestation.PrimaryKey);
                Assert.AreEqual(((SymmetricKeyAttestation)individualEnrollment.Attestation).SecondaryKey, symmetricKeyAttestation.SecondaryKey);
            }
            else if (attestationType == AttestationMechanismType.X509)
            {
                Assert.AreEqual(AttestationMechanismType.X509, attestationMechanism.Type);
                X509Attestation x509Attestation = (X509Attestation)attestationMechanism.GetAttestation();
                Assert.AreEqual(((X509Attestation)individualEnrollment.Attestation).GetPrimaryX509CertificateInfo().SHA1Thumbprint, x509Attestation.GetPrimaryX509CertificateInfo().SHA1Thumbprint);
                Assert.AreEqual(((X509Attestation)individualEnrollment.Attestation).GetSecondaryX509CertificateInfo().SHA1Thumbprint, x509Attestation.GetSecondaryX509CertificateInfo().SHA1Thumbprint);
            }
            else
            {
                Assert.AreEqual(AttestationMechanismType.Tpm, attestationMechanism.Type);
                TpmAttestation tpmAttestation = (TpmAttestation)attestationMechanism.GetAttestation();
                Assert.AreEqual(((TpmAttestation)individualEnrollment.Attestation).EndorsementKey, tpmAttestation.EndorsementKey);
                Assert.AreEqual(((TpmAttestation)individualEnrollment.Attestation).StorageRootKey, tpmAttestation.StorageRootKey);
            }
        }
예제 #11
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["deviceid"];


            string primaryKey = "";
            var    credential = new ChainedTokenCredential(
                new ManagedIdentityCredential(),
                new VisualStudioCodeCredential());
            var client = new SecretClient(new Uri("https://deviceonboardingkeyvault.vault.azure.net/"), credential);
            var secret = client.GetSecret("dpsconnectionstring");

            using (var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(secret.Value.Value)){
                var attestation = new SymmetricKeyAttestation("", "");
                var ie          = new IndividualEnrollment(name, attestation);
                var enrollment  = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(ie);

                var keys = enrollment.Attestation as SymmetricKeyAttestation;
                primaryKey = keys.PrimaryKey;
                log.LogInformation(enrollment.IotHubHostName);
            }

            return(new OkObjectResult(primaryKey));
        }
        public async Task ProvisioningServiceClient_GetIndividualEnrollmentAttestation(AttestationMechanismType attestationType)
        {
            using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(TestConfiguration.Provisioning.ConnectionString);
            string registrationId = AttestationTypeToString(attestationType) + "-" + Guid.NewGuid();

            IndividualEnrollment individualEnrollment = await CreateIndividualEnrollmentAsync(
                provisioningServiceClient,
                registrationId,
                attestationType,
                null,
                null,
                AllocationPolicy.Static,
                null,
                null,
                null,
                Logger)
                                                        .ConfigureAwait(false);

            AttestationMechanism attestationMechanism = null;
            await RetryOperationHelper
            .RetryOperationsAsync(
                async() =>
            {
                attestationMechanism = await provisioningServiceClient.GetIndividualEnrollmentAttestationAsync(individualEnrollment.RegistrationId);
            },
                s_provisioningServiceRetryPolicy,
                s_retryableExceptions,
                Logger)
            .ConfigureAwait(false);

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

            if (attestationType == AttestationMechanismType.SymmetricKey)
            {
                attestationMechanism.Type.Should().Be(AttestationMechanismType.SymmetricKey);

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

                var x509Attestation = (X509Attestation)attestationMechanism.GetAttestation();
                x509Attestation.GetPrimaryX509CertificateInfo().SHA1Thumbprint.Should().Be(((X509Attestation)individualEnrollment.Attestation).GetPrimaryX509CertificateInfo().SHA1Thumbprint);
                x509Attestation.GetSecondaryX509CertificateInfo().SHA1Thumbprint.Should().Be(((X509Attestation)individualEnrollment.Attestation).GetSecondaryX509CertificateInfo().SHA1Thumbprint);
            }
            else
            {
                attestationMechanism.Type.Should().Be(AttestationMechanismType.Tpm);

                var tpmAttestation = (TpmAttestation)attestationMechanism.GetAttestation();
                tpmAttestation.EndorsementKey.Should().Be(((TpmAttestation)individualEnrollment.Attestation).EndorsementKey);
                tpmAttestation.StorageRootKey.Should().Be(((TpmAttestation)individualEnrollment.Attestation).StorageRootKey);
            }
        }
예제 #13
0
        private static async Task <IndividualEnrollment> EnrollToDpsAsync(string primaryKey, string secondKey, string registeredId, string provisionConnString)
        {
            using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(ProvisionConnString);
            IndividualEnrollment device = null;

            try
            {
                device = await provisioningServiceClient.GetIndividualEnrollmentAsync(registeredId).ConfigureAwait(false);
            }
            catch (ProvisioningServiceClientException ex)
            {
                // device is not existed
            }

            // if device is not existed, create device in DPS
            if (device == null)
            {
                Attestation attestation          = new SymmetricKeyAttestation(primaryKey, secondKey);
                var         individualEnrollment =
                    new IndividualEnrollment(
                        registeredId,
                        attestation)
                {
                    // TODO check device id region and set region IoTHub service host name
                    IotHubHostName = "connect-iothub-dev.azure-devices.net"
                };

                device = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment);
            }

            return(device);
        }
예제 #14
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);
        }
예제 #15
0
        private static async Task <AttestationMechanism> GetIndividualAttestationAsync(string registeredId)
        {
            using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(ProvisionConnString);
            var attestationMechanism = await provisioningServiceClient.GetIndividualEnrollmentAttestationAsync(registeredId);

            return(attestationMechanism);
        }
예제 #16
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
            }
        }
예제 #17
0
        private ProvisioningServiceClient CreateProvisioningServiceWithProxy(string proxyServerAddress)
        {
            HttpTransportSettings transportSettings = new HttpTransportSettings();

            transportSettings.Proxy = new WebProxy(proxyServerAddress);

            return(ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString, transportSettings));
        }
예제 #18
0
        public DpsEnrollmentGroup(IConfiguration config, ILoggerFactory loggerFactory)
        {
            Configuration = config;
            _logger       = loggerFactory.CreateLogger <DpsEnrollmentGroup>();

            _provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(
                Configuration.GetConnectionString("DpsConnection"));
        }
예제 #19
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
            }
        }
예제 #20
0
        private static ProvisioningServiceClient GetProvisioningServiceClient()
        {
            if (_provisioningServiceClient == null)
            {
                _provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(ProvisionServiceConnectionString);
            }

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

                try
                {
                    if (this.Name != null)
                    {
                        client.DeleteEnrollmentGroupAsync(this.Name).GetAwaiter().GetResult();
                    }
                    else
                    {
                        QueryResult enrollments = client.CreateEnrollmentGroupQuery(new QuerySpecification("select * from enrollments")).NextAsync().GetAwaiter().GetResult();
                        foreach (PSEnrollmentGroups enrollment in IotDpsUtils.ToPSEnrollmentGroups(enrollments.Items))
                        {
                            client.DeleteEnrollmentGroupAsync(enrollment.EnrollmentGroupId).GetAwaiter().GetResult();
                        }
                    }

                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(true);
                    }
                }
                catch
                {
                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(false);
                    }
                }
            }
        }
예제 #22
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
            }
        }
        /// <summary>
        /// Creates the provisioning service client instance
        /// </summary>
        /// <param name="proxyServerAddress">The address of the proxy to be used, or null/empty if no proxy will be used</param>
        /// <returns>the provisioning service client instance</returns>
        public static ProvisioningServiceClient CreateProvisioningService(string proxyServerAddress)
        {
            var transportSettings = new Devices.Provisioning.Service.HttpTransportSettings();

            if (!string.IsNullOrWhiteSpace(proxyServerAddress))
            {
                transportSettings.Proxy = new WebProxy(proxyServerAddress);
            }

            return ProvisioningServiceClient.CreateFromConnectionString(Configuration.Provisioning.ConnectionString, transportSettings);
        }
예제 #24
0
        private static async Task <IoTHubResponse> UpdateExistDeviceKeysAsync(string beckmanConnectId, string iotHubConnectionString)
        {
            using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(ProvisionConnString);
            var individualEnrollmentResult = await provisioningServiceClient.GetIndividualEnrollmentAsync(beckmanConnectId);

            var primaryKey = ComputeDerivedSymmetricKey(Guid.NewGuid().ToString());
            var secondKey  = ComputeDerivedSymmetricKey(Guid.NewGuid().ToString());

            // update dps keys
            Attestation attestation = new SymmetricKeyAttestation(primaryKey, secondKey);

            individualEnrollmentResult.Attestation = attestation;

            var updateDpsResult = await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollmentResult);

            if (updateDpsResult.RegistrationId == beckmanConnectId)
            {
                // update IoTHub keys (rollback or errors when failed)
                var registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
                var device          = await registryManager.GetDeviceAsync(beckmanConnectId);

                var newDevice = new Device(beckmanConnectId)
                {
                    ETag           = device.ETag,
                    Authentication = new AuthenticationMechanism
                    {
                        SymmetricKey = new SymmetricKey
                        {
                            PrimaryKey   = primaryKey,
                            SecondaryKey = secondKey
                        }
                    }
                };

                var deviceResponse = await registryManager.UpdateDeviceAsync(newDevice);

                if (string.IsNullOrWhiteSpace(deviceResponse.Id))
                {
                    var response = new IoTHubResponse
                    {
                        PrimaryKey = primaryKey,
                        SecondKey  = secondKey
                    };

                    return(response);
                }
            }

            return(null);
        }
예제 #25
0
        public static async Task <int> Main(string[] args)
        {
            if (args.Length > 0)
            {
                s_connectionString = args[0];
            }

            using var provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(s_connectionString);
            var sample = new CleanupEnrollmentsSample(provisioningServiceClient);
            await sample.RunSampleAsync();

            Console.WriteLine("Done.");
            return(0);
        }
예제 #26
0
        static async Task SetRegistrationDataAsync()
        {
            #region QueryingEnrollemnts
            Console.WriteLine("Fetching Existing Enrollments--------------------------------");
            using var serviceClient = ProvisioningServiceClient.CreateFromConnectionString(ServiceConnectionString);
            QuerySpecification qu = new QuerySpecification("SELECT * FROM enrollments");

            using (Query query = serviceClient.CreateIndividualEnrollmentQuery(qu))
            {
                while (query.HasNext())
                {
                    Console.WriteLine("\nQuerying the next enrollments...");
                    QueryResult queryResult = await query.NextAsync().ConfigureAwait(false);

                    Console.WriteLine(queryResult);
                }
            }
            Console.WriteLine("Enrollment Fetch Complete------------------------------------");
            #endregion

            #region CreateIndividualEnrollment
            Console.WriteLine("Starting SetRegistrationData");

            //Attestation attestation = X509Attestation.CreateFromClientCertificates(privateKey);


            var    pem        = System.IO.File.ReadAllText(@"D:\Code\Diality\CACerts\CACertificates\mydevice4-public.pem");
            string certBuffer = GetBytesFromPEM(pem, "CERTIFICATE");



            Attestation attestation = X509Attestation.CreateFromClientCertificates(certBuffer);



            IndividualEnrollment individualEnrollment = new IndividualEnrollment(SampleRegistrationId, attestation);

            individualEnrollment.DeviceId           = OptionalDeviceId;
            individualEnrollment.ProvisioningStatus = OptionalProvisioningStatus;
            individualEnrollment.IotHubHostName     = "vvk5cob-Iot-Hub-2.azure-devices.net";

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

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

            Console.WriteLine("\nIndividualEnrollment created with success.");
            Console.WriteLine(individualEnrollmentResult);
            #endregion
        }
        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 IoTHubHelper(IOptions <AppSettings> config, ILogger <IoTHubHelper> logger)
 {
     _logger                    = logger;
     _appSettings               = config.Value;
     _registryManager           = RegistryManager.CreateFromConnectionString(_appSettings.IoTHub.ConnectionString);
     _serviceClient             = ServiceClient.CreateFromConnectionString(_appSettings.IoTHub.ConnectionString);
     _digitalTwinClient         = DigitalTwinClient.CreateFromConnectionString(_appSettings.IoTHub.ConnectionString);
     _provisioningServiceClient = ProvisioningServiceClient.CreateFromConnectionString(_appSettings.Dps.ConnectionString);
     _dps_webhookUrl            = _appSettings.Dps.WebHookUrl;
     _deviceClient              = null;
     _isConnected               = false;
     _privateModelRepoUrl       = _appSettings.ModelRepository.repoUrl;
     _privateModelToken         = _appSettings.GitHub.token;
 }
예제 #29
0
        private async Task <SecurityProvider> CreateSecurityProviderFromName(string name, X509EnrollmentType?x509Type)
        {
            _verboseLog.WriteLine($"{nameof(CreateSecurityProviderFromName)}({name})");

            switch (name)
            {
            case nameof(SecurityProviderTpmHsm):
                var tpmSim = new SecurityProviderTpmSimulator(Configuration.Provisioning.TpmDeviceRegistrationId);

                string base64Ek       = Convert.ToBase64String(tpmSim.GetEndorsementKey());
                string registrationId = Configuration.Provisioning.TpmDeviceRegistrationId;


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

                _log.WriteLine($"Getting enrollment: RegistrationID = {registrationId}");
                IndividualEnrollment enrollment = await provisioningService.GetIndividualEnrollmentAsync(registrationId).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 nameof(SecurityProviderX509Certificate):

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

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

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

                return(new SecurityProviderX509Certificate(certificate, collection));
            }

            throw new NotSupportedException($"Unknown security type: '{name}'.");
        }
예제 #30
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.DpsName, DPSResources.RemoveRegistration))
            {
                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);

                try
                {
                    client.DeleteDeviceRegistrationStateAsync(this.RegistrationId).GetAwaiter().GetResult();

                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(true);
                    }
                }
                catch
                {
                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(false);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }